package com.dong.pointviewpager.widget

import android.content.Context
import android.util.AttributeSet
import android.widget.RelativeLayout
import com.dong.pointviewpager.interfaces.IPagerBean
import com.dong.pointviewpager.interfaces.listener.OnPagerStateChangedListener

/**
 * Created by Dong on 2018/3/13.
 */
open class PointViewPager<T: IPagerBean> @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : RelativeLayout(context, attrs, defStyleAttr), OnPagerStateChangedListener {

    var loopViewPager: LoopViewPager<T>? = null
        protected set
    var pointView: PointView? = null
        protected set

    init {
        initViewPager()
        initPointView()
    }

    /*
     * 初始化LoopViewPager
     */
    protected open fun initViewPager() {
        loopViewPager = LoopViewPager<T>(context).apply{
            onPagerStateChangedListener = this@PointViewPager
            layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        }
        addView(loopViewPager)
    }

    /*
     * 初始化小圆点
     */
    private fun initPointView() {
        pointView = PointView(context).apply {
            layoutParams =  LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT).apply{
                addRule(CENTER_HORIZONTAL)
                addRule(ALIGN_PARENT_BOTTOM)
            }
        }
        addView(pointView)
    }

    override fun onPagerDataChanged(itemCount: Int) {
        pointView?.run {
            count = itemCount
            initialise()
        }
    }

    override fun onPagerScroll(position: Int, offset: Float, positionOffsetPixels: Int) {
        pointView?.run {
            percent = position + offset
            initialise()
        }
    }
}